package com.example.myapplication.banner

import android.content.Context
import android.graphics.Bitmap
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.viewpager.widget.PagerAdapter
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.Target
import com.example.myapplication.R
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer
import java.util.concurrent.Executors


/**
 * Banner适配器
 */
class BannerAdapter(private val context: Context, private val onVideoPlayCompleted: (() -> Unit)? = null) : PagerAdapter() {
    private var dataList: List<BannerItem> = ArrayList()
    private var currentVideoViews: MutableMap<Int, StandardGSYVideoPlayer> = mutableMapOf()
    private var videoFrameImages: MutableMap<Int, ImageView> = mutableMapOf()

    fun setData(data: List<BannerItem>) {
        dataList = data
    }

    fun getItem(position: Int): BannerItem {
        // 添加边界检查
        if (dataList.isEmpty()) {
            throw IndexOutOfBoundsException("Data list is empty")
        }
        return dataList[position % dataList.size]
    }

    override fun getCount(): Int {
        return if (dataList.isEmpty()) 0 else Integer.MAX_VALUE
    }

    override fun isViewFromObject(view: View, obj: Any): Boolean {
        return view === obj
    }

    override fun instantiateItem(container: ViewGroup, position: Int): Any {
        // 添加数据检查
        if (dataList.isEmpty()) {
            val emptyView = View(context)
            container.addView(emptyView)
            return emptyView
        }

        val item = getItem(position)

        return when (item.type) {
            BannerItemType.IMAGE -> {
                val view = LayoutInflater.from(context).inflate(R.layout.item_image_banner, container, false)
                val imageView = view.findViewById<ImageView>(R.id.img_Image)
                // 使用网络图片作为示例
                Glide.with(context)
                    .load(item.url)
                    .placeholder(R.drawable.ic_default)
                    .into(imageView)
                container.addView(view)
                view
            }
            BannerItemType.VIDEO -> {
                val view = LayoutInflater.from(context).inflate(R.layout.item_video_banner, container, false)
                val videoView = view.findViewById<StandardGSYVideoPlayer>(R.id.videoView)
                val videoFrameImage = view.findViewById<ImageView>(R.id.videoFrameImage)
                // 设置真实的网络视频URI
                try {
                    // 配置GSYVideoPlayer
                    videoView.setUp(item.url, false, null)
                    
                    // 设置播放器的各种属性
//                    videoView.isShowFullAnimation = false
//                    videoView.isNeedLockFull = true
//                    videoView.isRotateViewAuto = false
//                    videoView.isShowPauseCover = false

//                    videoView.setThumbImageView(videoFrameImage)
                    // 显示视频首帧图像
                    showVideoFrame(videoFrameImage, item.url, position)

                    // 设置视频播放完成监听
                    videoView.setVideoAllCallBack(object : com.shuyu.gsyvideoplayer.listener.VideoAllCallBack {

                        override fun onStartPrepared(url: String?, vararg objects: Any?) {
                            Log.e("Ces","播放")
                        }

                        override fun onPrepared(url: String?, vararg objects: Any?) {
                            // 视频准备完成
                            videoFrameImage.postDelayed({videoFrameImage.visibility = View.GONE}, 200)
                        }

                        override fun onClickStartIcon(url: String?, vararg objects: Any?) {
                            // 点击播放按钮
                            Log.e("Ces","播放")
                        }

                        override fun onClickStartError(url: String?, vararg objects: Any?) {
                            // 点击播放出错
                        }

                        override fun onClickStop(url: String?, vararg objects: Any?) {
                        }

                        override fun onClickStopFullscreen(url: String?, vararg objects: Any?) {
                        }

                        override fun onAutoComplete(url: String?, vararg objects: Any?) {
                            // 视频播放完成
                            // 显示首帧图像
                            videoFrameImage.visibility = View.VISIBLE
                            // 通知BannerView视频播放完成
                            onVideoPlayCompleted?.invoke()
                        }

                        override fun onComplete(url: String?, vararg objects: Any?) {
                            Log.e("Ces","播放")
                        }

                        override fun onPlayError(url: String?, vararg objects: Any?) {
                            // 播放出错时也显示首帧图像
//                            videoFrameImage.visibility = View.VISIBLE
                            //播放出错播放下一个
                            onVideoPlayCompleted?.invoke()
                        }

                        // 其他回调方法可以留空或根据需要实现
                        override fun onClickResume(url: String?, vararg objects: Any?) {}
                        override fun onClickResumeFullscreen(url: String?, vararg objects: Any?) {
                        }

                        override fun onClickSeekbar(url: String?, vararg objects: Any?) {}
                        override fun onClickSeekbarFullscreen(url: String?, vararg objects: Any?) {}
                        override fun onEnterFullscreen(url: String?, vararg objects: Any?) {}
                        override fun onQuitFullscreen(url: String?, vararg objects: Any?) {}
                        override fun onQuitSmallWidget(url: String?, vararg objects: Any?) {}
                        override fun onEnterSmallWidget(url: String?, vararg objects: Any?) {}
                        override fun onTouchScreenSeekVolume(url: String?, vararg objects: Any?) {}
                        override fun onTouchScreenSeekPosition(url: String?, vararg objects: Any?) {}
                        override fun onTouchScreenSeekLight(url: String?, vararg objects: Any?) {}
                        override fun onClickStartThumb(url: String?, vararg objects: Any?) {}
                        override fun onClickBlank(url: String?, vararg objects: Any?) {}
                        override fun onClickBlankFullscreen(url: String?, vararg objects: Any?) {}
                    })

                    // 保存当前VideoView引用
                    currentVideoViews[position] = videoView
                    videoFrameImages[position] = videoFrameImage

                } catch (e: Exception) {
                    e.printStackTrace()
                }

                container.addView(view)
                view
            }
        }
    }

    /**
     * 显示视频首帧图像
     */
    private fun showVideoFrame(imageView: ImageView, videoUrl: String, position: Int) {
        // 使用后台线程获取视频首帧
        val executor = Executors.newSingleThreadExecutor()
        executor.execute {
            try {
                // 在主线程更新UI
                imageView.post {
                    Glide.with(context).asBitmap().load(videoUrl)
                        .thumbnail(Glide.with(context).asBitmap().load(videoUrl)).into(imageView)
                    imageView.visibility = View.VISIBLE
                }
            } catch (e: Exception) {
                e.printStackTrace()
                // 出错时显示默认图像
                imageView.post {
                    imageView.setImageResource(R.drawable.ic_default)
                    imageView.visibility = View.VISIBLE
                }
            }
        }
    }

    override fun destroyItem(container: ViewGroup, position: Int, obj: Any) {
        container.removeView(obj as View)

        // 移除对应的VideoView引用
        currentVideoViews.remove(position)
        videoFrameImages.remove(position)

        // 如果是视频视图，停止播放
        currentVideoViews[position]?.let { videoPlayer ->
            videoPlayer.onVideoPause()
        }
    }

    /**
     * 停止指定位置的视频播放
     */
    fun stopVideoPlayback(position: Int) {
        currentVideoViews[position]?.let { videoPlayer ->
            videoPlayer.onVideoPause()
            // 显示首帧图像
            videoFrameImages[position]?.let { imageView ->
                imageView.visibility = View.VISIBLE
            }
        }
    }

    /**
     * 暂停指定位置的视频播放（不显示首帧图像）
     */
    fun pauseVideoPlayback(position: Int) {
        // 添加空检查
        if (currentVideoViews.isEmpty()) return

        currentVideoViews[position]?.let { videoPlayer ->
            videoPlayer.onVideoPause()
        }
        videoFrameImages[position]?.let { imageView ->
            imageView.visibility = View.VISIBLE
        }
    }

    /**
     * 播放指定位置的视频
     */
    fun playVideo(position: Int) {
        // 添加空检查
        if (currentVideoViews.isEmpty()) return

        currentVideoViews[position]?.let { videoPlayer ->
            // 开始播放视频
            videoPlayer.startPlayLogic()
            // 隐藏首帧图像
//            videoFrameImages[position]?.let { imageView ->
//                imageView.postDelayed({imageView.visibility = View.GONE}, 500)
//            }
        }
    }

    /**
     * 释放所有资源
     */
    fun release() {
        for ((_, videoPlayer) in currentVideoViews) {
            videoPlayer.onVideoReset()
        }
        currentVideoViews.clear()
        videoFrameImages.clear()
    }
}